package com.entertainment.ticketing.controller;

import com.entertainment.ticketing.repository.EventInfoRepository;
import com.entertainment.ticketing.repository.OrderInfoRepository;
import com.entertainment.ticketing.repository.UserInfoRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/analytics")
public class AnalyticsController {
    private final EventInfoRepository eventRepo;
    private final OrderInfoRepository orderRepo;
    private final UserInfoRepository userRepo;

    public AnalyticsController(EventInfoRepository eventRepo, OrderInfoRepository orderRepo, UserInfoRepository userRepo) {
        this.eventRepo = eventRepo;
        this.orderRepo = orderRepo;
        this.userRepo = userRepo;
    }

    @GetMapping("/dashboard")
    public ResponseEntity<Map<String, Object>> dashboard() {
        Map<String, Object> data = new HashMap<>();
        data.put("tickets", eventRepo.count());
        data.put("users", userRepo.count());
        // 今日订单与收入
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        List<com.entertainment.ticketing.entity.OrderInfo> todayPaid = orderRepo.findByStatusAndCreatedAtBefore((byte)2, LocalDateTime.now());
        long ordersToday = todayPaid.stream().filter(o -> o.getCreatedAt().isAfter(startOfDay)).count();
        BigDecimal revenueToday = todayPaid.stream()
                .filter(o -> o.getCreatedAt().isAfter(startOfDay))
                .map(com.entertainment.ticketing.entity.OrderInfo::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        data.put("ordersToday", ordersToday);
        data.put("revenueToday", revenueToday);
        return ResponseEntity.ok(data);
    }

    @GetMapping("/sales-trend")
    public ResponseEntity<Map<String, Object>> salesTrend() {
        // 近7天：组装简单统计（示例数据或基于createdAt）
        List<String> labels = new ArrayList<>();
        List<Integer> values = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (int i = 6; i >= 0; i--) {
            LocalDateTime dayStart = now.minusDays(i).withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime dayEnd = dayStart.plusDays(1);
            int count = (int) orderRepo.findByStatusAndCreatedAtBefore((byte)2, dayEnd).stream()
                    .filter(o -> o.getCreatedAt().isAfter(dayStart))
                    .mapToInt(o -> o.getTicketCount() != null ? o.getTicketCount() : 0)
                    .sum();
            labels.add(String.format("%02d-%02d", dayStart.getMonthValue(), dayStart.getDayOfMonth()));
            values.add(count);
        }
        Map<String, Object> resp = new HashMap<>();
        resp.put("labels", labels);
        resp.put("values", values);
        return ResponseEntity.ok(resp);
    }

    @GetMapping("/ticket-distribution")
    public ResponseEntity<List<Map<String, Object>>> ticketDistribution() {
        // 简化：按分类统计数量
        List<com.entertainment.ticketing.entity.EventInfo> events = eventRepo.findAll();
        Map<String, Long> agg = new HashMap<>();
        for (var e : events) {
            String cat = Optional.ofNullable(e.getCategory()).orElse("其他");
            agg.put(cat, agg.getOrDefault(cat, 0L) + 1);
        }
        List<Map<String, Object>> data = new ArrayList<>();
        for (var entry : agg.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", entry.getKey());
            item.put("value", entry.getValue());
            data.add(item);
        }
        return ResponseEntity.ok(data);
    }

    @GetMapping("/recent-activities")
    public ResponseEntity<List<Map<String, Object>>> recentActivities() {
        List<Map<String, Object>> activities = new ArrayList<>();
        
        // 获取最近的订单活动
        List<com.entertainment.ticketing.entity.OrderInfo> recentOrders = orderRepo.findAll()
                .stream()
                .sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
                .limit(10)
                .toList();
        
        for (var order : recentOrders) {
            Map<String, Object> activity = new HashMap<>();
            activity.put("time", order.getCreatedAt().toString());
            
            // 正确访问用户信息
            String userName = "未知用户";
            if (order.getUser() != null) {
                if (order.getUser().getRealName() != null && !order.getUser().getRealName().trim().isEmpty()) {
                    userName = order.getUser().getRealName();
                } else if (order.getUser().getUsername() != null) {
                    userName = order.getUser().getUsername();
                } else {
                    userName = "用户" + order.getUser().getId();
                }
            }
            activity.put("user", userName);
            
            String action;
            String status;
            switch (order.getStatus()) {
                case 1 -> {
                    action = "创建了订单 #" + order.getOrderNo();
                    status = "待支付";
                }
                case 2 -> {
                    action = "支付了订单 #" + order.getOrderNo();
                    status = "成功";
                }
                case 3 -> {
                    action = "取消了订单 #" + order.getOrderNo();
                    status = "已取消";
                }
                case 4 -> {
                    action = "申请退款 #" + order.getOrderNo();
                    status = "退款中";
                }
                default -> {
                    action = "处理订单 #" + order.getOrderNo();
                    status = "处理中";
                }
            }
            
            activity.put("action", action);
            activity.put("status", status);
            activities.add(activity);
        }
        
        return ResponseEntity.ok(activities);
    }
}